<!-- src/views/BooksView.vue -->
<template>
  <div class="books-view">
    <el-container>
      <el-header>
        <div class="header-content">
          <h2>📚 图书列表</h2>
          <div class="header-buttons">
            <el-button type="primary" @click="goToBatchImport" icon="Upload">
              批量导入
            </el-button>
            <el-button type="primary" @click="goToCreate" icon="Plus">
              添加图书
            </el-button>
          </div>
        </div>
      </el-header>
      <el-main>
        <el-table
          :data="books"
          v-loading="loading"
          style="width: 100%"
          border
          :row-class-name="tableRowClassName"
        >
          <el-table-column prop="id" label="ID" width="60" align="center" />
          <el-table-column prop="isbn" label="ISBN" min-width="150" show-overflow-tooltip />
          <el-table-column prop="title" label="书名" min-width="180" show-overflow-tooltip />
          <el-table-column prop="author" label="作者" width="120" show-overflow-tooltip />
          <el-table-column prop="genre" label="分类" width="100" align="center" />
          <el-table-column label="出版日期" width="120" align="center">
            <template #default="scope">
              {{ formatDate(scope.row.publicationDate) }}
            </template>
          </el-table-column>
          <el-table-column label="状态" width="100" align="center">
            <template #default="scope">
              <el-tag
                :type="scope.row.available ? 'success' : 'danger'"
                effect="dark"
                size="small"
              >
                {{ scope.row.available ? '可借阅' : '不可借' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="库存" width="100" align="center">
            <template #default="scope">
              <span :class="{ 'low-stock': scope.row.availableCopies <= 2 }">
                {{ scope.row.availableCopies }} / {{ scope.row.totalCopies }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="220" fixed="right" align="center">
            <template #default="scope">
              <div class="action-buttons">
                <el-button
                  size="small"
                  type="primary"
                  @click="viewDetail(scope.row.id)"
                  icon="View"
                  circle
                />
                <el-button
                  size="small"
                  type="warning"
                  @click="borrowBook(scope.row)"
                  :disabled="!scope.row.available || scope.row.availableCopies <= 0"
                  icon="Upload"
                  circle
                  :title="getBorrowButtonTitle(scope.row)"
                />
                <el-button
                  size="small"
                  type="success"
                  @click="returnBook(scope.row)"
                  :disabled="scope.row.availableCopies >= scope.row.totalCopies"
                  icon="Download"
                  circle
                  title="归还图书"
                />
                <el-dropdown
                  @command="handleDropdownCommand"
                  :disabled="loading"
                >
                  <el-button size="small" type="info" circle>
                    <el-icon><MoreFilled /></el-icon>
                  </el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item
                        :command="{ action: 'edit', data: scope.row }"
                        icon="Edit"
                      >
                        编辑
                      </el-dropdown-item>
                      <el-dropdown-item
                        :command="{ action: 'delete', data: scope.row }"
                        icon="Delete"
                        divided
                      >
                        删除
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <el-empty
          v-if="!loading && books.length === 0"
          description="暂无图书数据"
          :image-size="100"
        >
          <el-button type="primary" @click="goToCreate">添加第一本图书</el-button>
        </el-empty>
      </el-main>
    </el-container>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { createBookService } from '@/services/bookServiceFactory'
import { format } from 'date-fns'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus,
  View,
  Upload,
  Download,
  MoreFilled,
  Edit,
  Delete
} from '@element-plus/icons-vue'

export default {
  name: 'BooksView',
  components: {
    // eslint-disable-next-line vue/no-unused-components
    Plus,
    // eslint-disable-next-line vue/no-unused-components
    View,
    // eslint-disable-next-line vue/no-unused-components
    Upload,
    // eslint-disable-next-line vue/no-unused-components
    Download,
    MoreFilled,
    // eslint-disable-next-line vue/no-unused-components
    Edit,
    // eslint-disable-next-line vue/no-unused-components
    Delete
  },
  setup() {
    const router = useRouter()
    const books = ref([])
    const loading = ref(false)
    const bookService = createBookService()

    const formatDate = (dateString) => {
      if (!dateString) return ''
      return format(new Date(dateString), 'yyyy-MM-dd')
    }

    const tableRowClassName = ({ row}) => {
      if (!row.available) {
        return 'unavailable-row'
      }
      return ''
    }

    const getBorrowButtonTitle = (book) => {
      if (!book.available) {
        return '图书不可借阅'
      }
      if (book.availableCopies <= 0) {
        return '库存不足'
      }
      return '借阅图书'
    }

    const loadBooks = async () => {
      try {
        loading.value = true
        books.value = await bookService.getAllBooks()
      } catch (error) {
        console.error('Failed to load books:', error)
        ElMessage.error('加载图书列表失败')
      } finally {
        loading.value = false
      }
    }

    const goToCreate = () => {
      router.push('/books/create')
    }

    const goToBatchImport = () => {
      router.push('/books/batch-import')
    }

    const viewDetail = (id) => {
      router.push(`/books/${id}`)
    }

    const borrowBook = async (book) => {
      try {
        await ElMessageBox.confirm(
          `确定要借阅《${book.title}》吗？`,
          '借阅确认',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )

        await bookService.borrowBook(book.id)
        ElMessage.success('借阅成功！')
        loadBooks()
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('借阅失败')
        }
      }
    }

    const returnBook = async (book) => {
      try {
        await ElMessageBox.confirm(
          `确定要归还《${book.title}》吗？`,
          '归还确认',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'info'
          }
        )

        await bookService.returnBook(book.id)
        ElMessage.success('归还成功！')
        loadBooks()
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('归还失败')
        }
      }
    }

    const handleDropdownCommand = async (command) => {
      const { action, data } = command
      const book = data

      if (action === 'edit') {
        router.push(`/books/${book.id}`)
      } else if (action === 'delete') {
        try {
          await ElMessageBox.confirm(
            `确定要删除《${book.title}》吗？此操作不可恢复！`,
            '删除确认',
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'error'
            }
          )

          await bookService.deleteBook(book.id)
          ElMessage.success('图书删除成功！')
          loadBooks()
        } catch (error) {
          if (error !== 'cancel') {
            ElMessage.error('删除失败')
          }
        }
      }
    }

    onMounted(() => {
      loadBooks()
    })

    return {
      books,
      loading,
      formatDate,
      tableRowClassName,
      getBorrowButtonTitle,
      goToCreate,
      goToBatchImport,
      viewDetail,
      borrowBook,
      returnBook,
      handleDropdownCommand
    }
  }
}
</script>

<style scoped>
.books-view {
  height: 100vh;
}
.el-header {
  background-color: #f5f7fa;
  padding: 0 20px;
  border-bottom: 1px solid #ebeef5;
}
.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 60px;
}
.header-buttons {
  display: flex;
  gap: 12px;
}
.el-main {
  padding: 20px;
}

.action-buttons {
  display: flex;
  justify-content: center;
  gap: 8px;
}

.action-buttons .el-button--circle {
  width: 32px;
  height: 32px;
  padding: 6px;
}

.unavailable-row {
  background-color: #f9f9f9 !important;
  color: #999 !important;
}

.low-stock {
  color: #e6a23c;
  font-weight: bold;
}

.el-table :deep(.cell) {
  padding: 8px 0;
}

@media (max-width: 768px) {
  .action-buttons {
    flex-direction: column;
    gap: 4px;
  }

  .el-table :deep(.el-table__body-wrapper) {
    overflow-x: auto;
  }
}
</style>